package org.example.java8.stream;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * @author 夏焰波
 * @date 2020-07-13 1:40
 */
public class StreamFind {
    public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //获取任意一个
        Optional<Integer> optional = stream.filter(i -> i % 2 == 0).findAny();
        System.out.println(optional.get());

        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //获取第一个
        Optional<Integer> optional2 = stream.filter(i -> i % 2 == 0).findFirst();
        System.out.println(optional2.get());
        optional2.ifPresent(System.out::println);
        System.out.println(optional2.filter(i -> i == 2).get());

        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //获取任意一个
        Optional<Integer> optional3 = stream.filter(i -> i > 10).findAny();
        //orElse，如果optional为null则返回-1
        System.out.println(optional3.orElse(-1));

        int result = find(new Integer[]{1, 2, 3, 4, 5, 6, 7}, -1, i -> i > 10);
        System.out.println(result);
    }

    private static int find(Integer[] values, int defaultValue, Predicate<Integer> predicate) {
        for (int i : values) {
            if (predicate.test(i))
                return i;
        }
        return defaultValue;
    }
}
